package com.fyzk.data.preference;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.util.Base64;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.bean.LoginResponse;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.update.CustomerCalls;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

import http.DataUtil.text.TextUtil;

import static android.content.Context.MODE_PRIVATE;

/**
 * 自动登录信息保存类（首选项）
 *
 * @author Administrator
 */
public class MySharedPreferences implements IntentParamUtils {

    private SharedPreferences sharedPreferences;
    private Editor editor;
    private volatile static MySharedPreferences instance = null;

    private final String AUTHTOKEN = "authtoken";
    private final String PHOTOURL = "photoUrl";
    private final String DIALOG_DATE = "dialog_date";
    private final String BALANCE = "balance";
    private final String FIRST = "first";
    private final String ACTIVITY_ID = "activity_ids";
    /**
     * 用户名
     */
    public static String OPEN = "openStatus";
    /**
     * userno (uuid)
     */
    private static String USERNO = "userno";
    /**
     * 用户名
     */
    public static String USERNAME = "userName";
    /**
     * 昵称
     */
    public static String ALIAS = "alias";
    /**
     * 登录过的用户名(用于"登录界面"自动提示输入框)
     */
    public static String USERNAMES = "userNames";
    /**
     * 保存APP版本
     */
    public static String SAVE_VERSION = "save_version";
    /**
     * 版本更新描述
     */
    public static String VERSION_UPDATE_DESCRIPTION = "update.description";
    /**
     * 版本更新的网址
     */
    public static String VERSION_UPDATE_URL = "update.url";
    /**
     * 用户登录状态
     */
    private static String LOGIN_STATUS = "loginStatus";
    /**
     * 当前版本支持彩种
     */
    private static String LOTTERYS = "lotterys";
    /**
     * 账户彩金
     */
    private static String LEFTMONEY = "leftMoney";
    /**
     * 账户彩金
     */
    private static String FREEZE = "freeze";
    private static String DRAWBALANCE = "drawbalance";
    private final String TUISONG = "tuisong";

    /**
     * 客服电话
     */
    private static String SERVICE_PHONE = "service_phone";

    /**
     * 客服QQ
     */
    private static String SERVICE_QQ = "service_qq";

    /**
     * 客服QQ
     */
    private static String DRAW_CONTENT = "draw_content";

    private static String HANDSEL_CONTENT = "handsel_content";

    /**
     * 二维码链接
     */
    private static String QR_URL = "qr_url";

    /**
     * 启动页图片
     */
    private static String SPLASH_IMAGE_URL = "splash_image_url";
    /**
     * 客服微信图片
     */
    private static String QQ_IMAGE_URL = "qq_image_url";
    /**
     * 最后一次显示中奖弹窗的时间
     */
    private static String LAST_SHOW_WINNING_POPUP = "last_show_winning_popup";

    public void setOpenStatus(boolean isOpen) {
        editor.putBoolean(OPEN, isOpen);
        editor.commit();
    }

    public boolean getOpenStatus() {
        return sharedPreferences.getBoolean(OPEN, false);
    }

    private MySharedPreferences() {
        sharedPreferences = App.getContext().getSharedPreferences("dwj", MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public static MySharedPreferences getInstance() {
        if (null == instance) {
            synchronized (MySharedPreferences.class) {
                if (null == instance) {
                    instance = new MySharedPreferences();
                }
            }
        }
        return instance;
    }

    public void setUserInfo(LoginResponse response) {

        editor.putString(USERNAME, response.getUsername());
        editor.putString(USERNO, response.getUserno());
        editor.putString(BALANCE, response.getBalance() + "");
        editor.putString(DRAWBALANCE, response.getDrawbalance() + "");
        editor.putString(AUTHTOKEN, response.getAccessToken());
        editor.commit();

    }

    public void setActiviyID(String activiyID) {
        editor.putString(ACTIVITY_ID, activiyID);
        editor.commit();
    }

    public String getActiviyID() {
        return sharedPreferences.getString(ACTIVITY_ID, "");
    }

    public LoginResponse getUserInfo() {

        LoginResponse response = new LoginResponse();
        response.setAccessToken(sharedPreferences.getString(AUTHTOKEN, ""));
        response.setBalance(sharedPreferences.getString(BALANCE, ""));
        response.setDrawbalance(sharedPreferences.getString(DRAWBALANCE, ""));
        response.setUsername(sharedPreferences.getString(USERNAME, ""));
        response.setUserno(sharedPreferences.getString(USERNO, ""));
        return response;

    }

    public boolean isFirst() {
        return sharedPreferences.getBoolean(FIRST, true);
    }

    public void setFirst(boolean first) {
        editor.putBoolean(FIRST, first);
        editor.commit();
    }

    public void setUserNo(String userno) {
        editor.putString(USERNO, userno);
        editor.commit();
    }

    public String getUserNo() {
        return sharedPreferences.getString(USERNO, "");
    }

    public void setUserName(String userName) {
        editor.putString(USERNAME, userName);
        editor.commit();
    }

    public String getUserName() {
        return sharedPreferences.getString(USERNAME, "");
    }

    /**
     * 别名（昵称）
     *
     * @param alias
     */
    public void setAlias(String alias) {
        editor.putString(ALIAS, alias);
        editor.commit();
    }

    private final String BRANCH = "branch";
    private final String COMPANYID = "companyid";

    /**
     * 保存应用分支
     *
     * @param branch
     */
    public void setBranch(String branch) {
        editor.putString(BRANCH, branch);
        editor.commit();
    }

    /**
     * 得到应用分支
     */
    public String getBranch() {
        return sharedPreferences.getString(BRANCH, "");
    }

    /**
     * 保存企业id
     *
     * @param companyid
     */
    public void setCompanyid(String companyid) {
        editor.putString(COMPANYID, companyid);
        editor.commit();
    }

    /**
     * 得到企业id
     */
    public String getCompanyid() {
        return sharedPreferences.getString(COMPANYID, "");
    }

    /**
     * 别名（昵称）
     *
     * @return
     */
    public String getAlias() {
        return sharedPreferences.getString(ALIAS, "");
    }

    public void setUserNames(String userNames) {
        editor.putString(USERNAMES, userNames);
        editor.commit();
    }

    public String getUserNames() {
        return sharedPreferences.getString(USERNAMES, "");
    }

    public void setSaveVersion(String version) {
        editor.putString(SAVE_VERSION, version);
        editor.commit();
    }

    public String getSaveVersion() {
        return sharedPreferences.getString(SAVE_VERSION, "");
    }

    public void setCustomerCalls(String customerCalls) {
        editor.putString(SERVICE_PHONE, customerCalls);
        editor.commit();
    }

    public CustomerCalls getCustomerCalls() {
        String string = sharedPreferences.getString(SERVICE_PHONE, "");
        if (!TextUtil.isEmpty(string)) {
            try {
                return JSON.parseObject(string, CustomerCalls.class);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public void setServiceQQ(String serviceQQ) {
        editor.putString(SERVICE_QQ, serviceQQ);
        editor.commit();
    }

    public String getServiceQQ() {
        return sharedPreferences.getString(SERVICE_QQ, "");
    }

    public void setQrUrl(String qrUrl) {
        editor.putString(QR_URL, qrUrl);
        editor.commit();
    }

    public String getQrUrl() {
        return sharedPreferences.getString(QR_URL, "");
    }


    public void setDrawContent(String drawContent) {
        editor.putString(DRAW_CONTENT, drawContent);
        editor.commit();
    }

    public String getDrawContent() {
        return sharedPreferences.getString(DRAW_CONTENT, "");
    }

    public void setHandselContent(String handselContent) {
        editor.putString(HANDSEL_CONTENT, handselContent);
        editor.commit();
    }

    public String getHandselContent() {
        return sharedPreferences.getString(HANDSEL_CONTENT, "");
    }

    public void setSplashImageUrl(String splashImageUrl) {
        editor.putString(SPLASH_IMAGE_URL, splashImageUrl);
        editor.commit();
    }

    public String getSplashImageUrl() {
        return sharedPreferences.getString(SPLASH_IMAGE_URL, "");
    }

    public void setQQImageUrl(String qqImageUrl) {
        editor.putString(QQ_IMAGE_URL, qqImageUrl);
        editor.commit();
    }

    public String getQQImageUrl() {
        return sharedPreferences.getString(QQ_IMAGE_URL, "");
    }

    /**
     * 保存用户登录状态(根据开机联网返回判断用户是否已经登录)
     */
    public void setLoginStatus(boolean isLogin) {
        editor.putBoolean(LOGIN_STATUS, isLogin);
        editor.commit();
    }

    public boolean getLoginStatus() {
        return sharedPreferences.getBoolean(LOGIN_STATUS, false);
    }

    public void setBalance(String leftMoney) {
        editor.putString(LEFTMONEY, leftMoney);
        editor.commit();
    }

    /**
     * 保存用户登录状态(根据开机联网返回判断用户是否已经登录)
     */
    public void setCurrentLotterys(String lotterys) {
        editor.putString(LOTTERYS, lotterys);
        editor.commit();
    }

    public String getCurrentLotterys() {
        return sharedPreferences.getString(LOTTERYS, "");
    }

    public String getBalance() {
        return sharedPreferences.getString(LEFTMONEY, "");
    }

    public void setFreeze(String freeze) {
        editor.putString(FREEZE, freeze);
        editor.commit();
    }

    public String getFreeze() {
        return sharedPreferences.getString(FREEZE, "");
    }

    public void setDrawbalance(String freeze) {
        editor.putString(DRAWBALANCE, freeze);
        editor.commit();
    }

    public String getDrawbalance() {
        return sharedPreferences.getString(DRAWBALANCE, "");
    }


    /**
     * 保存版本更新 描述
     *
     * @param description
     */
    public void setVersionUpdateDescription(String description) {
        editor.putString(VERSION_UPDATE_DESCRIPTION, description);
        editor.commit();
    }

    /**
     * 得到版本更新 描述
     *
     * @return
     */
    public String getVersionUpdateDescription() {
        return sharedPreferences.getString(VERSION_UPDATE_DESCRIPTION, "");
    }

    /**
     * 保存版本更新下载地址   (为空时 表示无更新)
     *
     * @param url
     */
    public void setVersionUpdateUrl(String url) {
        editor.putString(VERSION_UPDATE_URL, url);
        editor.commit();
    }

    /**
     * 得到版本更新下载地址
     *
     * @return
     */
    public String getVersionUpdateUrl() {
        return sharedPreferences.getString(VERSION_UPDATE_URL, "");
    }


    //======================	常规设置	=======================

    public void setAuthToken(String authtoken) {
        editor.putString("authtoken", authtoken);
        editor.commit();
    }

    public String getAuthtoken() {
        return sharedPreferences.getString(AUTHTOKEN, "");
    }


    public void setPhotoUrl(String photourl) {
        editor.putString(PHOTOURL, photourl);
        editor.commit();
    }

    public void saveDialogDate() {
        editor.putLong(DIALOG_DATE,System.currentTimeMillis());
        editor.commit();
    }

    public Long getDialogTime() {
        return sharedPreferences.getLong(DIALOG_DATE, 0l);
    }

    public String getPhotoUrl() {
        return sharedPreferences.getString(PHOTOURL, "");
    }

    /**
     * 保存上次首页中奖弹窗显示时间
     *
     * @param millis
     */
    public void setLastShowWinningPopup(long millis) {
        editor.putLong(LAST_SHOW_WINNING_POPUP, millis);
        editor.commit();
    }

    public long getLastShowWinningPopup() {
        return sharedPreferences.getLong(LAST_SHOW_WINNING_POPUP, 0);
    }

    public static String CHANNEL = "channel";

    public void setChannel(String channel) {
        editor.putString(CHANNEL, channel);
        editor.commit();
    }


    public String getChannel() {
        return sharedPreferences.getString(CHANNEL, "");
    }


    public boolean getTuiSong() {
        return sharedPreferences.getBoolean(TUISONG, true);
    }

    public void setTuiSong(boolean tuiSong) {
        editor.putBoolean(TUISONG, tuiSong);
        editor.commit();
    }

    /**
     * 保存实体类
     *
     * @param key
     * @param obj obj必须实现Serializable接口
     */
    public void setBetCodeBean(int key, Object obj) {

        if (obj instanceof Serializable) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                String string64 = new String(Base64.encode(baos.toByteArray(), 0));
                editor.putString("obj" + key, string64).commit();
                editor.commit();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            throw new IllegalArgumentException("the obj must implement Serializble");
        }
    }

    /**
     * 读取实体类
     *
     * @param key
     * @return
     */
    public Object getBetCodeBean(int key) {
        Object obj = null;
        try {
            String base64 = sharedPreferences.getString("obj" + key, "");
            if (base64.equals("")) {
                return null;
            }
            byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
            ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;

    }
}
